import path from './path.js'
import cache from './token.js'
// import jWeixin from 'weixin-js-sdk'
var $func = {
	//多账号缓存键值
	accounts_storage_keys: 'bl_user_account_list',
	//经纬度
	lng: 0,
	lat: 0,
	location: {},
	can_click: {},
	/* 判断是否在微信中 */
	isWechat: function() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			// 微信客户端 
			return true;
		} else {
			// 不是微信客户端 
			uni.showModal({
				title: '提示',
				content: '请在微信浏览器中打开',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						// console.log('用户点击确定');
					}
				}
			});
			return false;
		}
	},
	/* 获取sdk初始化配置 */
	initJssdk(callback) {
		let that = this
		let url = window.location.href.split('#')[0];
		let data = {
			url: url
		}
		request.user.jssdk(data).then(res => {
			jWeixin.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: res.data.appId, // 必填，公众号的唯一标识
				timestamp: Number(res.data.timestamp), // 必填，生成签名的时间戳
				nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
				signature: res.data.signature, // 必填，签名
				jsApiList: ["openLocation", "getLocation"] // 必填，需要使用的JS接口列表
			});
			/* wx.hideAllNonBaseMenuItem(); */
			jWeixin.checkJsApi({
				jsApiList: ['openLocation', 'getLocation'] // 需要检测的JS接口列表，所有JS接口列表见附录2
			});
			//jWeixin.error(function(res){
			//	console.log(res)
			// config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
			//});
			if (callback) {
				callback(res.data);
			}

		})
	},
	//在需要定位页面调用  
	getlocation: function(callback) {
		if (!this.isWechat()) {
			//console.log('不是微信客户端')  
			return;
		}
		this.initJssdk(function(res) {
			jWeixin.ready(function() {
				jWeixin.getLocation({
					type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'  
					success: function(res) {
						// console.log(res); 
						uni.setStorageSync('getLocation', true)
						callback(res)
					},
					fail: function(res) {
						callback(res)
					},
				});
			});
		});
	},
	//打开位置  
	openlocation: function(latitude, longitude, name, address) {
		if (!this.isWechat()) {
			//console.log('不是微信客户端')  
			return;
		}
		this.initJssdk(function(res) {
			jWeixin.ready(function() {
				jWeixin.openLocation({ //根据传入的坐标打开地图  
					latitude: Number(latitude),
					longitude: Number(longitude),
					name: address, // 位置名
					address: name, // 地址详情说明
					scale: 16, // 地图缩放级别,整型值,范围从1~28。默认为最大,
					success: function() {
						console.log('ok')
					}
				});
			});
		});
	},
	get_location_auth(func) {
		let system = uni.getSystemInfoSync(); // 获取系统信息
		if (system.platform === 'android') { // 判断平台
			var context = plus.android.importClass("android.content.Context");
			var locationManager = plus.android.importClass("android.location.LocationManager");
			var main = plus.android.runtimeMainActivity();
			var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
			if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
				uni.showModal({
					title: '提示',
					content: '请打开定位服务功能',
					showCancel: false, // 不显示取消按钮
					success() {
						if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
							var Intent = plus.android.importClass('android.content.Intent');
							var Settings = plus.android.importClass('android.provider.Settings');
							var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							main.startActivity(intent); // 打开系统设置GPS服务页面
						} else {
							console.log('GPS功能已开启');
						}
					}
				});
			} else {
				func()
			}
		}
	},
	set_online_status() {

	},

	goLogin() {
		let that = this;
		that.WxLogin()
	},

	judgeNum(num) {
		if (num > 1000) {
			num = (num / 1000).toFixed(1) + 'k';
		}
		return num
	},

	goOtherLogin() {
		uni.navigateTo({
			// #ifdef MP-WEIXIN
			url: '/pages/index/uni-login',
			//#endif
			// #ifdef APP-PLUS || H5
			url: '/pages/index/login',
			//#endif
		})
	},

	getPageCode() {
		if (uni.getStorageSync("youthToken") == '') {
			const code = this.GetUrlParam('code');
			if (code !== null && code !== '') {
				this.login(code)
			}
			// else{
			// 	this.WxLogin();
			// }
		}
	},

	GetUrlParam(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
		var r = window.location.search.substr(1).match(reg)
		if (r != null) return unescape(r[2])
		return null
	},

	WxLogin() {
		const code = this.GetUrlParam('code')
		const local = window.location.href
		window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			path.appid + '&redirect_uri=' + encodeURIComponent(local) +
			'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'

		// window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
		// 	'wx99c5b70471d12e5c' + '&redirect_uri=' + encodeURIComponent(local) +
		// 	'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
	},

	login(code) {
		var data = {
			code: code
		}
		request.user.weChat(data).then(res => {
			uni.setStorageSync('youthToken', res.data.token)
			uni.setStorageSync('user', res.data.user)
			window.history.go(-2);
		})
	},

	minuTime(date1) {
		var date2 = new Date(); //结束时间
		var date3 = new Date(date1).getTime() - date2.getTime(); //时间差的毫秒数
		var subMinutes = Math.floor(date3 / (60 * 1000)) //获取总共的分钟差
		//计算出相差天数
		var days = Math.floor(date3 / (24 * 3600 * 1000))
		//计算出小时数
		var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000))
		//计算相差分钟数
		var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / (60 * 1000))
		//计算相差秒数
		var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
		var seconds = Math.round(leave3 / 1000)
		let timeData = {};
		timeData.days = days < 0 ? 0 : days;
		timeData.hours = hours < 0 ? 0 : hours;
		timeData.minutes = minutes < 0 ? 0 : minutes;
		timeData.seconds = seconds < 0 ? 0 : seconds;
		return [date3, JSON.stringify(timeData)]
	},

	//上传图片
	upImage(func) {
		uni.chooseImage({
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log('filepath', tempFilePaths[0])
				this.upload(tempFilePaths[0], func);
			},
		});
	},
	upload(filePath, func) {
		this.loading('上传中...');
		uni.uploadFile({
			url: path.reqUrl, //仅为示例，非真实的接口地址
			filePath: filePath,
			name: "file",
			header: {
				Authorized: uni.getStorageSync('youthToken'),
			},
			success: (uploadFileRes) => {
				func instanceof Function && func(uploadFileRes)
				// console.log(JSON.parse(uploadFileRes.data));
				// let url = JSON.parse(uploadFileRes.data).data.url;
				// url = this.getImgUrl(url);
				// self.form.shop_img.push(url);
			},
			complete: () => {
				uni.hideLoading()
			}
		});
	},
	back(delta = 1) {
		uni.navigateBack({
			delta: delta
		})
	},
	return_back(res, delta = 1, msg = 'msg') {
		this.msg(res.msg)
		setTimeout(() => {
			this.back(delta)
		}, 500)
	},
	json_decode(string) {
		try {
			return JSON.parse(string)
		} catch (err) {
			return null
		}
	},
	set_back(key, value = '') {
		var pages = getCurrentPages();
		var prepage = pages[pages.length - 2]; //上一个页面
		if (typeof key == 'string') {
			prepage.$vm[key] = value;
		} else if (typeof key == 'object') {
			Object.assign(prepage.$vm, key)
		}
		this.back()
	},
	hide_mobile(mobile) {
		return mobile ? (mobile.slice(0, 3) + '****' + mobile.slice(7)) : ''
	},
	bigImage(list, func) {
		wx.previewImage({
			urls: list, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
			current: '', // 当前显示图片的http链接，默认是第一个
			success: function(res) {
				func instanceof Function && func()
			},
			fail: function(res) {},
			complete: function(res) {},
		})
	},
	//发送验证码
	send_sms(mobile, func) {
		if (!this.is_mobile(mobile)) {
			this.msg('手机号格式错误')
			return
		}

		this.get('sms_code', {
			mobile: mobile
		}, res => {
			func instanceof Function && func()
		})
	},
	is_mobile(mobile) {
		return /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(mobile)
	},
	//验证是否登录
	validate: function() {
		if (uni.getStorageSync('youthToken') == '') {
			this.toLogin();
		}
	},
	//格式化返回u-upload图片路径
	return_upload: function(obj, ref = 'uUpload', is_array = false) {
		let list = []
		obj.$refs[ref].lists.forEach((v) => {
			list.push(v.response.data.url)
		})
		if (is_array === true) {
			return list
		} else {
			return JSON.stringify(list)
		}
	},
	//登录页
	toLogin: function() {
		uni.redirectTo({
			url: '/pages/signIn/signIn'
		})
	},
	//首页
	toIndex: function() {
		uni.switchTab({
			url: '/pages/index/index'
		})
	},
	//个人中心
	toUser: function() {
		uni.switchTab({
			url: '/pages/mine/my'
		})
	},
	//信息弹出
	msg: function(msg, type = 'none', duration = 2000) {
		uni.showToast({
			icon: type,
			title: msg,
			duration: duration
		});
	},
	loading: function(title, mask = true) {
		uni.showLoading({
			title: title,
			mask: mask,
		})
	},
	more: 'nomore',
	load: false,
	request: function(url, data, method = 'GET') {
		let that = this;
		let header = {
			'content-type': 'application/json',
			'Authorization': 'Bearer ' + cache.getCache('youthToken')
		};
		return new Promise((resolve, reject) => {
			uni.request({
				method: method,
				url: path.apiUrl + url,
				data: data,
				header: header,
				dataType: 'json',
			}).then((response) => {
				let [error, res] = response;
				if (res.data.status_code == 401) {
					uni.hideLoading();
				}
				if (res.data.status_code == 200) {
					resolve(res.data);
				} else {
					resolve(res.data);
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 3000
					})
					//其他异常
					return false;
				}
			}).catch(error => {
				let [err, res] = error;
				reject(err)
			})
		});
	},
	show_img(img = '') {
		if (img.indexOf('//') !== -1) {
			return img;
		} else {
			return path.imgUrl + img
		}
	},
	randomString(e = 32) {
		var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
			a = t.length,
			n = "";
		for (i = 0; i < e; i++) {
			n += t.charAt(Math.floor(Math.random() * a));
		}
		return n
	},
	downImage(img_url) {
		var _this = this;
		uni.showModal({
			content: '是否下载',
			buttonText: ['确定', '取消'],
			success: (res) => {
				if (res.confirm) {
					uni.downloadFile({
						url: img_url,
						success: (res) => {
							if (res.statusCode === 200) {
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function() {
										_this.msg('保存成功')
									},
									fail: function() {
										_this.msg('保存失败');
									}
								});
							}
						}
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
	},
	serialize(obj) {
		let arr = [];
		for (let i in obj) {
			arr.push(i + '=' + obj[i]);
		}
		return arr.join('&')
	},
	update(host, click = false) {
		this.post(host + 'v1/banben.php', res => {
			var banben;
			var url;
			if (uni.getSystemInfoSync().platform == 'ios') {
				banben = res.data.data.banben_pingguo;
				url = res.data.data.url_pingguo
			}
			if (uni.getSystemInfoSync().platform == 'android') {
				banben = res.data.data.banben;
				url = res.data.data.url
			}

			if (banben != plus.runtime.version) {
				uni.showModal({
					title: '有新的版本,是否更新' + plus.runtime.version + '|' + banben,
					success: function(data) {
						if (data.confirm) {
							uni.showLoading({
								title: '加载中',
								mask: true,
							})
							var dtask = plus.downloader.createDownload(url, {}, function(d,
								status) {
								// 下载完成  
								if (status == 200) {
									plus.runtime.install(plus.io
										.convertLocalFileSystemURL(d
											.filename), {}, {},
										function(error) {
											this.msg('安装失败')
										})
								} else {
									this.msg('更新失败')
								}
							});
							dtask.start();
						} else {
							if (click === false) {
								plus.runtime.quit();
							}
						}
					},
					fail: function() {
						plus.runtime.quit();
					}
				});
			} else {
				if (click === true) {
					this.msg('已是最新版本')
				}
			}
		})
	},
	//复制
	copy(text, msg) {
		uni.setClipboardData({
			data: text,
			success: function() {
				uni.showToast({
					title:msg+'复制成功',
					icon:'none'
				})
				// console.log(msg + '复制成功');
			},
			fail: function(e) {
				// console.log(msg + '复制失败', e)
			}
		});
	},
	//打电话
	callPhone(phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		});
	},
	jump(url) {
		uni.navigateTo({
			url: url
		})
	}
}

uni.$func = $func

const install = Vue => {
	Vue.prototype.$func = $func
}

export default {
	install
}